package com.dq.health.service.impl;

import com.dq.health.dao.gen.GeneratorIdMapper;
import com.dq.health.entity.gen.GeneratorId;
import com.dq.health.enums.GeneratorIdTypeEnum;
import com.dq.health.service.IAPIGeneratorIdService;
import com.dq.health.utils.NumberUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class GeneratorIdService implements IAPIGeneratorIdService {
    private static final Logger LOGGER = LoggerFactory.getLogger(GeneratorIdService.class);

    @Resource
    private GeneratorIdMapper generatorIdMapper;

    @Override
    public synchronized String genId(GeneratorIdTypeEnum type) {
        Assert.notNull(type, "type cannot be null");

        String seqName = type.value();
        String newId = type.name();
        Date now = new Date();

        GeneratorId seq = generatorIdMapper.queryNextSeqByName(seqName);

        // 如果当前时间与最后生成时间不在同一天, 则重1开始
        if (!DateUtils.isSameDay(now, seq.getGenTime())) {
            seq.setGenCount(0L);
            seq.setGenId(newId + "-" + DateFormatUtils.format(now, "yyyyMMdd") + "-"
                + NumberUtil.fillZero(seq.getGenCount().intValue() + 1, 6));
            seq.setGenCount(1L);
        }

        newId = newId + "-" + DateFormatUtils.format(now, "yyyyMMdd") + "-"
            + NumberUtil.fillZero(seq.getGenCount().intValue() + 1, 6);
        generatorIdMapper.updateSeqByName(seqName, seq.getGenCount() + 1, newId, now);

        LOGGER.info("新生成的编码:{}", seq.getGenId());
        return seq.getGenId();
    }

    @Override
    public String genNumber(GeneratorIdTypeEnum type) {
        Assert.notNull(type, "type cannot be null");

        String seqName = type.value();
        String newId = "";
        Date now = new Date();

        GeneratorId seq = generatorIdMapper.queryNextSeqByName(seqName);

        // 如果当前时间与最后生成时间不在同一天, 则重1开始
        if (!DateUtils.isSameDay(now, seq.getGenTime())) {
            seq.setGenCount(0L);
            seq.setGenId(DateFormatUtils.format(now, "yyyyMMdd") + "-"
                + NumberUtil.fillZero(seq.getGenCount().intValue() + 1, 8));
            seq.setGenCount(1L);
        }

        newId =
            DateFormatUtils.format(now, "yyyyMMdd") + "-" + NumberUtil.fillZero(seq.getGenCount().intValue() + 1, 8);
        generatorIdMapper.updateSeqByName(seqName, seq.getGenCount() + 1, newId, now);

        return seq.getGenId();
    }

}
